<template>
  <div class="k-btn-wrap">
    <div
      v-show="cp_col.count === 8"
      class="num-nav fl"
      :style="{height: number_nav_h, top: '-' + number_nav_h, left: '-' + number_nav_l}"
    >
      <ul
        class="nav-ul"
        :style="pcStyle"
      >
        <li
          v-for="(li, idx) in cp_col.list"
          :key="idx"
          class="nav-li"
          :class="{active: select === idx}"
          @touchstart.stop="touchStart(``, $event)"
          @mousedown.stop="mouseDown(``, $event)"
          @touchend.stop="navClick(idx)"
          @mouseup.stop="navClick(idx)"
          @touchmove.stop="touchMove"
          @mousemove.stop="mouseMove"
        >
          <span class="nav-btn">{{ li }}</span>
        </li>
      </ul>
    </div>
    <div
      class="num-mask fl"
      :class="{'sym-center': cp_col.count === 8}"
    >
      <ul
        class="sy-ul num-ul"
        :class="'index-' + select"
      >
        <li
          v-for="(row, idx) in cp_ordinary"
          :key="idx"
          class="clear-fix k-row k-row-4"
        >
          <span
            v-for="(btn, i) in row.items"
            :key="i"
            class="fl k-btn"
            :class="['k-' + btn.type, {active: active === `${idx}_${i}`}, 'k-btn-' + (cp_col.count - 1)]"
            @touchend.stop="btnClick($event, btn)"
            @mouseup.stop="btnClick($event, btn)"
            @touchstart.stop="touchStart(`${idx}_${i}`, $event)"
            @mousedown.stop="mouseDown(`${idx}_${i}`, $event)"
            @touchmove.stop="touchMove"
            @mousemove.stop="mouseMove"
          >{{ btn.view || btn.text }}
            <span class="k-btn-bg" />
          </span>
        </li>
      </ul>
    </div>
    <ul class="fr sym-ul sym-pad">
      <li
        v-for="(row, idx) in cp_board.large"
        :key="idx"
        class="k-row"
        :class="{['k-row-' + cp_board.large.length]: 1}"
      >
        <template v-for="(btn, i) in row">
          <span
            v-if="btn.expect === 'delete'"
            :key="i"
            class="k-btn"
            :class="['k-' + btn.type, 'k-btn-' + cp_board.large[0].length, {active: active === `r_${idx}_${i}`}]"
            @touchstart.stop="deleteClick($event, btn, `r_${idx}_${i}`)"
            @touchend.stop="pressUp"
            @mousedown.stop="deleteClick($event, btn, `r_${idx}_${i}`)"
            @mouseup.stop="pressUp"
            @click.stop="pressClick($event, btn)"
          ><span class="k-btn-bg" /></span>
          <span
            v-else
            :key="i"
            class="k-btn"
            :class="['k-' + btn.type, 'k-btn-' + cp_board.large[0].length, {active: active === `r_${idx}_${i}`, disable: disableBtn.indexOf(btn.expect) > -1}]"
            @touchstart.stop="symStart(`r_${idx}_${i}`, $event)"
            @touchend.stop="btnClick($event, btn)"
            @mousedown.stop="symStart(`r_${idx}_${i}`, $event)"
            @mouseup.stop="btnClick($event, btn)"
          >{{ btn.view || btn.text }}</span>
        </template>
      </li>
    </ul>
  </div>
</template>

<script>
/******************/
/******************/
// region    //import
import { KeepPress } from './index';
import { $debounce, browerEnv } from './utils';

// endregion
// region    //export

export default {
    name: 'TheSymbol',
    props: {
        boardData: {
            type: Object,
            required: true,
        },
        payload: {
            type: Object,
            default () {
                return {};
            },
        },
        boardModel: {
            type: String,
            default: '',
        },
        disableBtn: {
            type: Array,
            default: () => {
                return [];
            },
        },
    },
    data () {
        let press = new KeepPress();
        return {
            pressDown: press.down(($event, data) => {
                this.active = '';
                this.$emit('keep-press', $event, data);
            }, 1000),
            pressUp: press.up((e) => {
                if (this.mobile) {
                    let { type } = e || window.event;
                    if (type.match(/mouse/g)) {
                        return false;
                    }
                }
                this.active = '';
                this.$emit('btn-click', e, {
                    'text': '删除',
                    'type': 'symbol delete',
                    'expect': 'delete',
                });
            }),
            pressClick: press.click(($event, data) => {
                if (this.mobile) {
                    let { type } = $event || window.event;
                    if (type.match(/mouse/g)) {
                        return false;
                    }
                }
                this.active = '';
                this.$emit('btn-click', $event, data);
            }),
            touchMove: $debounce(({ touches }) => {
                let { clientX, clientY } = touches[0];
                let { x, y } = this.touche;
                if (Math.abs(clientX - x) > 10 || Math.abs(clientY - y) > 10) {
                    this.defaultClick = true;
                    this.active = '';
                }
            }, 40, 'fixed', true),
            mouseMove: $debounce((e) => {
                let { clientX, clientY } = e;
                let { x, y } = this.touche;
                if (Math.abs(clientX - x) > 10 || Math.abs(clientY - y) > 10) {
                    this.defaultClick = true;
                    this.active = '';
                }
            }, 40, 'fixed', true),
            active: '',
            select: 0,
            touche: { x: 1, y: 0 },
            pool: {
                number: 9,
                letters: 3,
                chinese: 2,
                combo: 1,
            },
            defaultClick: false,
            mobile: browerEnv().android || browerEnv().ios,
        };
    },
    computed: {
        cp_board () {
            let { defaultSymbol, large } = this.boardData.keysText;
            let { symbols, prevBoardType } = this.boardData;
            let temp = [
                {
                    items: Object.entries(defaultSymbol).map(([k, itm]) => Object.assign({}, itm, { text: k })),
                    name: '默认',
                },
            ];
            if (symbols.length > 0) temp = symbols;
            if (prevBoardType) {
                large = [...large, [{
                    text: '中/英',
                    expect: 'goback',
                    type: 'symbol',
                }]];
            }
            return {
                ordinary: temp,
                large,
            };
        },
        cp_ordinary () {
            console.log(this.cp_board, this.cp_col, 'cp_board');
            let name = this.cp_col.list[this.select];
            let select = this.cp_board.ordinary.findIndex(itm => {
                return name === undefined && true || itm.name === name;
            });
            let arr = this.cp_board.ordinary[select].items;
            let res = [
                {
                    count: 0,
                    items: [],
                },
            ];
            let col = this.cp_col.count;
            if (select === 0) {
                let small = arr.filter(itm => !itm.type.includes('double')).slice(0, this.pool[this.boardData.prevBoardType] || 0);
                arr = arr.filter(itm => !small.find(s => s === itm));
            }
            arr.forEach(itm => {
                let temp = null;
                let vLength = itm.type.includes('double') && 2 || 1;
                temp = res.find(ele => (ele.count + vLength < col));
                if (temp) {
                    temp.count += vLength;
                    temp.items.push(itm);
                } else {
                    res.push({
                        count: vLength,
                        items: [itm],
                    });
                }
            });
            return res;
        },
        cp_col () {
            let count = 8;
            if (this.cp_board.ordinary.length > 1) count = 8;
            return {
                count,
                list: this.cp_board.ordinary.filter((itm, idx) => {
                    if (idx === 0) {
                        return this.payload.fullFirst;
                    }
                    return true;
                }).map(itm => itm.name),
            };
        },
        number_nav_h () {
            let aimtooldivH = document.querySelector('.aimtooldiv').offsetHeight;
            let result;
            // if (!this.mobile) {
            if (aimtooldivH < 45) {
                result = 45;
            } else {
                result = aimtooldivH;
            }
            // }
            return result + 'px';
        },
        number_nav_l () {
            return 1 + 'px';
        },
        pcStyle () {
            return !this.mobile ? {
                paddingBottom: 0,
                height: '100%',
            } : {};
        },
    },
    watch: {
        boardData: {
            deep: true,
            immediate: true,
            handler () {
                let i = this.cp_col.list.findIndex(v => v === this.boardModel);
                this.select = Math.max(0, i);
            },
        },
    },
    methods: {
        btnClick ($event, count) {
            if (this.mobile) {
                let { type } = $event || window.event;
                if (type.match(/mouse/g)) {
                    return false;
                }
            }
            if (this.defaultClick) return;
            this.active = '';
            this.$emit('btn-click', $event, count);
        },
        deleteClick ($event, btn, cls) {
            if (this.mobile) {
                let { type } = $event || window.event;
                if (type.match(/mouse/g)) {
                    return false;
                }
            }
            this.active = cls;
            this.defaultClick = false;
            this.pressDown($event, btn);
        },
        symStart (arg, $event) {
            if (this.mobile) {
                let { type } = $event || window.event;
                if (type.match(/mouse/g)) {
                    return false;
                }
            }
            this.active = arg;
            this.defaultClick = false;
        },
        touchStart (p = '', { touches: { 0: { clientX: x, clientY: y } } }) {
            Object.assign(this.touche, { x, y });
            this.active = p;
            this.defaultClick = false;
        },
        mouseDown (p = '', { clientX: x, clientY: y, type }) {
            if (this.mobile) {
                if (type.match(/mouse/g)) {
                    return false;
                }
            }
            Object.assign(this.touche, { x, y });
            this.active = p;
            this.defaultClick = false;
        },
        navClick (idx) {
            if (this.defaultClick) return;
            this.select = idx;
            this.$emit('on-model', {
                boardModel: this.cp_col.list[idx],
            })
        },
    },
};

// endregion

/******************/
/******************/
// region    //function

// endregion

</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">

    // @font-face {
    //     font-family: 'spe-symbol';  /* project id 780790 */
    //     /*src: url('//at.alicdn.com/t/font_780790_vo3lyx8hy1.eot'),*/
    //     /*url('//at.alicdn.com/t/font_780790_vo3lyx8hy1.eot?#iefix') format('embedded-opentype');*/
    //     src: url('../fonts/symbol/iconfont.woff') format('woff'),
    //     url('../fonts/symbol/iconfont.ttf') format('truetype');
    //     /*url('//at.alicdn.com/t/font_780790_vo3lyx8hy1.svg#spe-symbol') format('svg');*/
    // }

  .k-btn-wrap .k-btn {
    font-family: 'customFont1', 'customFont2', "Microsoft YaHei", "sans serif", "Tahoma", "Helvetica", "Arial", 'spe-symbol';
    &.delete {

    }
  }

  .num-nav {
    // width: calc(14% - 10px);
    // margin-right: 10px;
    // height: 100%;
    // border-right: 1px solid #ccc;
    overflow: hidden;
    position: absolute;
    width: 100%;
  }

  .num-mask {
    height: 100%;
    padding-bottom: 4px;
    overflow: hidden;
  }

  .sym-center {
    width: calc((100% - 64px) / 8 * 7 + 52px);
    .k-btn-6 {
    }
  }

  .num-ul {
    height: 100%;
    width: 100%;
    overflow-y: auto;
    padding: 4px 0 4px 10px;
    &.index-4 .k-btn {
      font-family: 'customFont', 'customFont1', 'customFont2', "Microsoft YaHei", "sans serif", "Tahoma", "Helvetica", "Arial", 'spe-symbol';;
    }
  }
  .nav-ul {
    overflow-x: auto;
    height: calc(100% + 20px);
    padding-bottom: 20px;
    overflow-y: hidden;
    width: 100%;
    // padding-right: 24px;
    background: #efefef;
    display: flex;
    justify-content: flex-start;
  }

  .sym-pad {
    height: 100%;
    width: calc((100% - 64px) / 8 + 12px);
    padding: 4px 4px 8px 8px;
  }

  .k-btn-wrap {
    position: relative;
    padding: 0;
    background: #f5f7f8;
  }

  .k-btn-box {
    z-index: 0;
  }

  .nav-li {
    height: 100%;
    flex: 0 0 100px;
    text-align: center;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    // border-right: 1px solid #ccc;
    white-space: nowrap;
    font-size: 80%;
    &:last-child{
      border-right: none;
    }
    &.active {
      // background: #fff;
      color: #13d098;
    }
  }

  @media screen and (max-width: 600px) {
    .num-nav {
      width: 100%;
      margin-right: 0;
    }

    .num-ul {
      padding: 10px 10px 10px 10px;
    }

    .nav-ul {
      padding-left: 0;
      .nav-li{
        flex: 0 0 50px;
      }
    }

    .sy-ul {
      padding-left: 4px;
    }
    .sym-pad {
      padding: 10px 10px 10px 4px;
    }
  }

</style>
